import { String } from "core-js";

let Vue;
class VueRouter {
    constructor(opts){
        this.$opts = opts;
        const initUrl = window.location.hash.slice(1) || "/";
        // this._vm = new Vue({
        //     data: {
        //         current: initUrl
        //     }
        // });
        Vue.util.defineReactive(this, 'current', initUrl)
        window.addEventListener('hashchange', () => {
            this.current = window.location.hash.slice(1)
        })
    }
}
VueRouter.install = function(_Vue) {
    Vue = _Vue;
    // 挂着$router属性 局混入目的：延迟下面逻辑到router创建完毕并且附加到选项上时才执行
    Vue.mixin({
        beforeCreate() {
            if(this.$options.router) {
                

                Vue.prototype.$router = this.$options.router;
                
            }
        },
    });
    Vue.component('router-link', {
        props: {
            to: {
                type: String,
                required: true,
                }
        },
        render(h) {
            return h(
                'a',
                {
                    attrs: {
                        href: `#${this.to}`
                    },
                },
                this.$slots.default
            );
        },
    });
    Vue.component('router-view', {
        render(h) {
            let component = null;
            let route = this.$router.$opts.routes.find(ele => ele.path === this.$router.current);
            // console.log(Vue.prototype);
            // console.log(this.$$data);
            if(route) {
                component = route.component
            }
            return h(component);
        },
    });
    }

export default VueRouter;